package cn.b.sky.user;

import cn.b.sky.user.service.LoginLogService;
import cn.b.sky.user.service.model.LoginLog;
import cn.b.sky.user.service.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 
 * <strong>Title : AuthenticationSuccessHandler.java<br></strong>
 * <strong>Package : cn.b.sky.user.security<br></strong>
 * <strong>Description : </strong>重写登录成功处理器，记录登录日志<br> 
 * <strong>Create on : 2015-8-31 下午6:23:03<br></strong>
 * <p>
 * @author lidapeng<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 * <strong>修改历史:</strong><br>
 * 修改人 | 修改日期 | 修改描述<br>
 * -------------------------------------------<br>
 * <br>
 * <br>
 */
@Component
@Slf4j
public class AuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

  @Autowired
  private LoginLogService loginLogService;

  @Override
  public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                      Authentication authentication) throws IOException, ServletException {
    this.setDefaultTargetUrl("/manage/index");
    this.setAlwaysUseDefaultTargetUrl(Boolean.TRUE);
    saveLoginLog(request);
    super.onAuthenticationSuccess(request, response, authentication);
  }

  private void saveLoginLog(HttpServletRequest request) {
    try {
      UserInfo user = SecurityContextUtil.getCurrentUser();
      LoginLog log = new LoginLog();
      log.setSiteCode(user.getSiteCode());
      log.setUserCode(user.getUserCode());
      log.setUserText(user.getUserText());
      String ip = SecurityContextUtil.getCurrentUserLoginIp();
      log.setIpAddress(ip);
      //log.setMacAddress(SecurityContextUtil.getCurrentUserMacAddress(ip));
      log.setSessionId(request.getSession(false).getId());
      loginLogService.saveLoginLog(log);
    } catch (Exception e) {
      log.error("{}", e);
    }
  }

  public void setLoginLogService(LoginLogService loginLogService) {
    this.loginLogService = loginLogService;
  }
}
